#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 1. 给表格创建行列数目（2 个），从 0 开始
    ui->tableWidget->insertRow(0); ui->tableWidget->insertRow(1);
    ui->tableWidget->insertColumn(0); ui->tableWidget->insertColumn(1);
    // 2. 设置列名
    ui->tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("工号"));
    ui->tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("姓名"));
    // 3. 插入数据
    ui->tableWidget->setItem(0,0, new QTableWidgetItem("1001"));
    ui->tableWidget->setItem(0,1, new QTableWidgetItem("张三"));
    ui->tableWidget->setItem(1,0, new QTableWidgetItem("1002"));
    ui->tableWidget->setItem(1,1, new QTableWidgetItem("王五"));
}

void Widget::on_pushButton_insertRow_clicked()
{
    int rowCount = ui->tableWidget->rowCount();
    // 在最后一行进行新增 注意：此处参数是 "下标"
    ui->tableWidget->insertRow(rowCount);
}

void Widget::on_pushButton_deleteRow_clicked()
{
    // 获取当前选中行号 再删除
    int curRow = ui->tableWidget->currentRow();
    ui->tableWidget->removeRow(curRow);
}

void Widget::on_pushButton_insertCol_clicked()
{
    int colCount = ui->tableWidget->columnCount();
    ui->tableWidget->insertColumn(colCount);
    // 新增一列，还有设置列名
    QString text = ui->lineEdit->text();
    ui->tableWidget->setHorizontalHeaderItem(colCount, new QTableWidgetItem(text));
}

void Widget::on_pushButton_deleteCol_clicked()
{
    int curCol = ui->tableWidget->currentColumn();
    ui->tableWidget->removeColumn(curCol);
}

Widget::~Widget()
{
    delete ui;
}
